<?php
/**
 * Site3TempoResolver.php
 *
 * Description
 *
 * @author Milkmeowo <milkmeowo@gmail.com>
 */

namespace App\Resolver;
use App\Exceptions\NotExistCateException;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use App\Parser\Site3TempoParser;

class Site3TempoResolver
{
    private $client;

    private $cookie;

    const CATE = [
        'BEST_PAGE' => 64,
        'MADE_PAGE' => 69,
        'OUTER_PAGE' => 24,
        'TOP_PAGE' => 25,
        'BOTTOM_PAGE' => 26,
        'DRESS_PAGE' => 27,
        'SHOES_AND_BAG_PAGE' => 28,
        'ACC_PAGE' => 29,
    ];

    protected $cate;

    protected $currentPage;

    /**
     * @return mixed
     */
    public function getCate()
    {
        return $this->cate;
    }

    /**
     * @param mixed $cate
     */
    public function setCate($cate)
    {
        $this->cate = $cate;
    }

    /**
     * Site3TempoResolver constructor.
     *
     * @param $client
     */
    public function __construct($cate, $currentPage = null)
    {
        $this->cate = $cate;
        if(!in_array($cate, self::CATE)){
            throw new NotExistCateException();
        }
        $this->currentPage = isset($currentPage) ? $currentPage : 1;

        $this->client = new Client([
            'base_uri' => 'http://www.3tempo.co.kr',
            //'proxy' => [
            //    'http'  => 'tcp://127.0.0.1:1080',
            //    'https' => 'tcp://127.0.0.1:1080'
            //]
        ]);
        $this->cookie = new CookieJar();
    }

    /**
     * @return mixed
     */
    public function getCurrentPage()
    {
        return $this->currentPage;
    }

    /**
     * @param mixed $currentPage
     */
    public function setCurrentPage($currentPage)
    {
        $this->currentPage = $currentPage;
    }

    /**
     * Helper function to get html of a page
     * @param $path
     * @return string
     */
    public function getPage($path)
    {
        return $this->client->get($path)->getBody()->getContents();
    }

    public function getCatePage()
    {
        $query = http_build_query([
           'cate_no' => $this->cate,
           'page' => $this->currentPage
        ]);
        $catePageUrl = 'product/list.html?' . $query;
        return $response = $this->getPage($catePageUrl);
    }

    public function getPageProducts()
    {
        $array = [];

        $html = $this->getCatePage();
        Site3TempoParser::getAllProducts($html, $array);

        return $array;
    }

    public function getFirstProduct()
    {
        $array = [];

        $html = $this->getCatePage();
        Site3TempoParser::getFirstProduct($html, $array);

        return $array;
    }

    public function getCategoryName()
    {
        $html =  $this->getCatePage();
        return Site3TempoParser::getNameOfCategory($html);
    }
}